package com.dlz.systemshop.pojo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 董熠涛
 * @date 2025/4/25 13:44
 */
@Data
public class LogUser implements UserDetails{

    private User user;

    private List<String> perms;

    @JsonIgnore
    private List<GrantedAuthority> authorities;

    public LogUser(User user) {
        this.user = user;
    }

    public LogUser(List<String> perms, User user) {
        this.perms = perms;
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        authorities = new ArrayList<>();

        for (String perm : perms) {
//            将权限字符串 perm 封装为一个 SimpleGrantedAuthority 对象,
//            将多个 SimpleGrantedAuthority 对象添加到 authorities 列表中，形成用户的权限集合
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(perm);
                authorities.add(simpleGrantedAuthority);
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return UserDetails.super.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return UserDetails.super.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return UserDetails.super.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return UserDetails.super.isEnabled();
    }
}
